package com.jie.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 曾豪杰
 * @Date: 2022/09/10/18:25
 * @Description:
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    @Pointcut("execution(* com.jie.*.*.*(..))")
    public void log(){}

    @Before("log()")
    public void Before(JoinPoint joinPoint){
        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request=attributes.getRequest();
            String url=request.getRequestURI();
            String ip=request.getRemoteAddr();
            String classMethod=joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
            Object[] args=joinPoint.getArgs();
            RequestLog reuqestLog= new RequestLog(url, ip, classMethod, args);
            log.info("调用的Request:{}",reuqestLog);
        }else {
            log.warn("切面开始attributes为空");
        }

    }

    @After("log()")
    public void After(){
//        log.info("");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void AfterReturn(Object result){
        log.info("调用的result:{}",result);
    }

    private static class RequestLog{
        private final String url;
        private final String ip;
        private final String classMethod;
        private final Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
